import type { IntensityMetrics } from '@/lib/mediapipe/intensity';

export interface AIIntensityFeedback {
  intensityScore: number;
  feedback: string;
  suggestions: string[];
  encouragement: string;
  rawText: string;
}

export interface AIIntensityEvaluatorOptions {
  apiKey: string;
  baseUrl?: string;
  model?: string;
}

const DEFAULT_MODEL = 'ernie-4.5-0.3b';
const DEFAULT_BASE_URL = 'https://aistudio.baidu.com/llm/lmapi/v3';

export class AIIntensityEvaluator {
  private apiKey: string;
  private baseUrl: string;
  private model: string;

  constructor(options: AIIntensityEvaluatorOptions) {
    this.apiKey = options.apiKey;
    this.baseUrl = options.baseUrl ?? DEFAULT_BASE_URL;
    this.model = options.model ?? DEFAULT_MODEL;
  }

  async generateFeedback(metrics: IntensityMetrics): Promise<AIIntensityFeedback> {
    const prompt = this.buildPrompt(metrics);

    try {
      const response = await fetch(`${this.baseUrl}/chat/completions`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          Authorization: `Bearer ${this.apiKey}`,
        },
        body: JSON.stringify({
          model: this.model,
          messages: [
            {
              role: 'user',
              content: prompt,
            },
          ],
          stream: false,
          extra_body: {
            penalty_score: 1,
          },
          max_completion_tokens: 800,
          temperature: 0.7,
          top_p: 0.85,
          frequency_penalty: 0,
          presence_penalty: 0,
        }),
      });

      const data = await response.json();

      const text = data?.choices?.[0]?.message?.content?.trim() ?? '';
      return this.parseFeedback(text, metrics);
    } catch (error) {
      console.error('AI intensity feedback error:', error);
      return this.fallbackFeedback(metrics);
    }
  }

  private buildPrompt(metrics: IntensityMetrics) {
    return `你是一名体能教练，请根据以下实时运动指标，判断运动强度并给出鼓励：

- 动作幅度：${(metrics.amplitude * 100).toFixed(1)}%
- 持续时间进度：${(metrics.durationRatio * 100).toFixed(1)}%
- 动作频率进度：${(metrics.frequencyRatio * 100).toFixed(1)}%
- 动作质量：${(metrics.quality * 100).toFixed(1)}%
- 综合强度：${(metrics.overallScore * 100).toFixed(1)}%
- 已完成时长：${metrics.elapsedSeconds.toFixed(1)} 秒
- 动作计数：${metrics.repCount}

请以以下结构回答：
强度评分：0-100 之间的整数
鼓励：一句充满活力的鼓励
建议：列出 2-3 条简单可执行的建议
`;
  }

  private parseFeedback(text: string, metrics: IntensityMetrics): AIIntensityFeedback {
    let intensityScore = Math.round(metrics.overallScore * 100);
    let feedback = '保持节奏，继续加油！';
    const suggestions: string[] = [];
    let encouragement = '太棒了，继续保持！';

    text.split('\n').forEach((line) => {
      const trimmed = line.trim();
      if (trimmed.startsWith('强度评分')) {
        const match = trimmed.match(/(\d{1,3})/);
        if (match) intensityScore = Number(match[1]);
      } else if (trimmed.startsWith('鼓励')) {
        feedback = trimmed.replace(/鼓励[:：]/, '').trim();
      } else if (trimmed.startsWith('建议')) {
        const content = trimmed.replace(/建议[:：]/, '').trim();
        const parts = content.split(/[、,，]/).map((s) => s.trim()).filter(Boolean);
        suggestions.push(...parts);
      }
    });

    if (suggestions.length === 0) {
      suggestions.push('保持呼吸稳定', '注意核心收紧');
    }

    encouragement = feedback || encouragement;

    return {
      intensityScore,
      feedback,
      suggestions: suggestions.slice(0, 3),
      encouragement,
      rawText: text,
    };
  }

  private fallbackFeedback(metrics: IntensityMetrics): AIIntensityFeedback {
    const score = Math.round(metrics.overallScore * 100);
    let feedback = '很好，保持节奏！';
    if (score < 30) feedback = '再加把劲，尝试加大动作幅度';
    if (score > 70) feedback = '状态很棒，继续保持！';

    return {
      intensityScore: score,
      feedback,
      suggestions: ['保持呼吸节奏', '注意动作幅度', '保持核心收紧'],
      encouragement: feedback,
      rawText: feedback,
    };
  }
}
